package _06_动态规划;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class _638_大礼包 {

    Map<List<Integer>, Integer> memo = new HashMap<>();

    public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        int num = price.size();
        // 过滤不是优惠价格的大礼包
        List<List<Integer>> filterSpecial = new ArrayList<>();
        for (List<Integer> list : special) {
            int totalPrice = 0;
            int totalCount = 0;
            for (int i = 0; i < num; i++) {
                totalCount += list.get(i);
                totalPrice += list.get(i) * price.get(i);
            }
            if (totalCount > 0 && totalPrice > list.get(num)) {
                filterSpecial.add(list);
            }
        }
        return dfs(price, filterSpecial, needs);
    }

    private int dfs(List<Integer> price, List<List<Integer>> filterSpecial, List<Integer> needs) {
        if (!memo.containsKey(needs)) {

            // 计算不花费大礼包锁使用的价钱
            int count = price.size();
            int minPrice = 0;
            for (int i = 0; i < count; i++) {
                minPrice += needs.get(i) * price.get(i);
            }
            // 计算购买大礼包
            for (List<Integer> list : filterSpecial) {
                List<Integer> nextNeeds = new ArrayList<>();
                for (int i = 0; i < count; i++) {
                    int subCount = needs.get(i) - list.get(i);
                    if (subCount < 0) break;
                    // 可以购买大礼包
                    nextNeeds.add(subCount);
                }
                if (count == nextNeeds.size()) {
                    minPrice = Math.min(minPrice, dfs(price, filterSpecial, nextNeeds) + list.get(count));
                }
            }
            memo.put(needs, minPrice);
        }
        return memo.get(needs);
    }

}
